package su.jet.irc.server.domain;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import su.jet.common.irc.domain.User;
import su.jet.common.irc.protocol.Session;
import su.jet.irc.datagateway.DataAccess;
import su.jet.irc.server.service.DataService;
import su.jet.irc.server.service.RequestHandler;

public class ChatServer {

	private static final int PORT_NUM = 10001;
	public static Set<User> registeredUsers; 
	public static Map<User, Session> onlineUsers; //[ek] TODO try DI here for better testability
	public static final String DATA_FILE_PATH = "res/registeredUsers.ser";
	public static final String DB_NAME = "chat";
	
	
	public static void main(String[] args) throws ClassNotFoundException, IOException, SQLException {
				
		DataService dataService = new DataService(new DataAccess(DB_NAME));
		registeredUsers = dataService.loadRegisteredUsersFromDB();
		
		onlineUsers = new HashMap<User, Session>();
		ServerSocket providerSocket = new ServerSocket(PORT_NUM);
				
		while (true) {
			System.out.println("waiting for connection...");
			Socket connection = providerSocket.accept();
			System.out.printf("client %s connected\n\n", connection);
			
			Session session = new Session(connection);
			
			Thread requestHandlerThread = new Thread(
					new RequestHandler(session, registeredUsers, onlineUsers, dataService));
			requestHandlerThread.start();
		}
	}
}
